<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { createImageViewer } from '@/components/ImageViewer'
import { createVideoViewer } from '@/components/VideoPlayer'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import {
  videoDetailPageListApi,
  delSysVideoDetailApi,
  updateThumbnailImageApi,
  videoTypeListApi,
  generateAudioApi
} from '@/api/resLibrary/video'
import { reactive, unref, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElTag, ElButton, ElMessage, ElSwitch } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import axios from 'axios'
const addVideoDetailModel = ref()
const editVideoDetailModel = ref()
const { push } = useRouter()
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import EditVideoDetailModel from './components/editVideoDetailModel.vue'
import { MINIO_HTTP } from '@/constants'
import { BaseButton } from '@/components/Button'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await videoDetailPageListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...searchParams.value
    })
    return {
      list: res.data.records,
      total: res.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, setProps, refresh } = tableMethods
const { t } = useI18n()

const searchParams = ref({})
const setSearchParams = (params: any) => {
  params.videoTypeId = params.videoTypeName
  delete params['videoTypeName']
  searchParams.value = params
  getList()
}
const columns = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    align: 'center',
    headerAlign: 'center',
    search: {
      hidden: true
    }
  },
  {
    field: 'fileName',
    headerAlign: 'center',
    align: 'center',
    label: '名称',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      },
      detail: {
        span: 24
      }
    }
  },
  {
    field: 'videoTypeName',
    headerAlign: 'center',
    align: 'center',
    label: '类别',
    search: {
      component: 'Select',
      optionApi: async () => {
        const res = await videoTypeListApi({})
        return res.data.map((v) => ({
          label: v.name,
          value: v.id
        }))
      }
    },
    form: {
      colProps: {
        span: 24
      },
      detail: {
        span: 24
      }
    }
  },
  {
    field: 'thumbnailUrl',
    label: '缩略图',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center',
    width: 200,
    slots: {
      default: (data: any) => {
        const aa = ref('')
        aa.value = MINIO_HTTP + data.row.thumbnailUrl
        return (
          <>
            <img src={aa.value} width="160" height="80" />
          </>
        )
      }
    }
  },
  {
    field: 'videoTime',
    label: '时长(秒)',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center'
  },
  {
    field: 'thumbnailTime',
    label: '缩略图(帧)',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center'
  },
  {
    field: 'startPlayTime',
    label: '片头时长',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center'
  },
  {
    field: 'status',
    label: '状态',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center',
    slots: {
      default: (data: any) => {
        return (
          <ElTag
            type={data.row.status === 2 ? 'success' : data.row.status === 1 ? 'warning' : 'danger'}
          >
            {data.row.status === 2 ? '学习完成' : data.row.status === 1 ? '学习中' : '未学习'}
          </ElTag>
        )
      }
    }
  },
  {
    field: 'sortNum',
    label: '排序',
    search: { hidden: true },
    headerAlign: 'center',
    align: 'center'
  },
  {
    field: 'video',
    align: 'center',
    headerAlign: 'center',
    width: '100px',
    label: '视频',
    search: { hidden: true },
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton
              type="primary"
              size="small"
              icon={<Icon icon="ep:video-play" />}
              onClick={() => {
                createVideoViewer({
                  url: MINIO_HTTP + data.row.fileUrl
                })
              }}
            >
              预览
            </BaseButton>
          </>
        )
      }
    }
  },
  {
    field: 'video',
    align: 'center',
    headerAlign: 'center',
    width: '100px',
    label: '音频',
    search: { hidden: true },
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton
              v-show={data.row.audioFlag === 1}
              size="small"
              type="primary"
              icon={<Icon icon="ep:video-play" />}
              onClick={() => {
                createVideoViewer({
                  url: MINIO_HTTP + data.row.audioUrl
                })
              }}
            >
              预览
            </BaseButton>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    width: '200px',
    headerAlign: 'center',
    label: t('tableDemo.action'),
    search: { hidden: true },
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton
              type="info"
              text
              onClick={() => generateAudio(data.row)}
              style="padding:0px "
            >
              生成音频
            </BaseButton>
            <BaseButton
              type="info"
              text
              onClick={() => updateThumbnailImage(data.row)}
              style="padding:0px "
            >
              更新
            </BaseButton>
            <BaseButton type="info" style="padding:0px" text onClick={() => action(data.row)}>
              编辑
            </BaseButton>
            <BaseButton
              type="success"
              style="padding:0px"
              text
              onClick={() => downloadFile(data.row)}
            >
              下载
            </BaseButton>
            <BaseButton type="danger" style="padding:0px" text onClick={() => delAction(data.row)}>
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const currentRow = ref(null)
// @ts-ignore
const { allSchemas } = useCrudSchemas(columns)
const action = (row) => {
  row.displayTime = new Date().getMilliseconds()
  currentRow.value = row
  editVideoDetailModel.value.isShowVideoDetailModel()
}
const AddAction = () => {
  addVideoDetailModel.value.isShowVideoDetailModel()
}
const delAction = (row) => {
  const aa = { id: row.id }
  delSysVideoDetailApi(aa)
    .then((res) => {
      if (res.code == '00000') {
        ElMessage({ message: '删除成功！', type: 'success' })
        getList()
      }
    })
    .finally(() => {})
}
const openImageUrl = (imageUrl) => {
  console.log('imageurl')
  createImageViewer({ urlList: [imageUrl] })
}
const generateAudio = (row) => {
  const arr = []
  arr.push(row.id)
  generateAudioApi({ ids: arr }).then((res) => {
    if (res.code == '00000') {
      ElMessage({ message: '更新成功！', type: 'success' })
      getList()
    }
  })
}
const updateThumbnailImage = (row) => {
  updateThumbnailImageApi({ id: row.id }).then((res) => {
    if (res.code == '00000') {
      ElMessage({ message: '更新成功！', type: 'success' })
      getList()
    }
  })
}
const onSearch = (value) => {
  console.log(value, '00000')
  getList()
}
const downloadFile = (row) => {
  // window.location = MINIO_HTTP + row.fileUrl
  const fileUrl = MINIO_HTTP + row.fileUrl
  axios
    .get(fileUrl, { responseType: 'blob' })
    .then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', row.fileName)
      document.body.appendChild(link)
      link.click()
    })
    .catch((error) => {
      console.error(error)
    })
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      showAction
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @refresh="refresh"
    />
  </ContentWrap>
  <EditVideoDetailModel
    @on-search="onSearch"
    ref="editVideoDetailModel"
    :current-row="currentRow"
  />
</template>
